
// const API_BASE_URL = 'https://test.tbx-tec.cn'
const API_BASE_URL = 'https://t.tbx-tec.cn'
let times = 0
// import {
//   Base64
// } from 'js-base64/base64.js';

let token = ''
let getToken = false

const request = (url, method = "get", data ={}, hasCheck = false) => {
  let _url = API_BASE_URL + url
  return new Promise((resolve, reject) => {
    uni.request({
      url: _url,
      method: method,
      data: data,
      header: {
        "Content-Type": "application/json",
        'Access-Token': uni.getStorageSync('token'),
		"X-Access-Token" : uni.getStorageSync('etoken'),
		platform : "",
		merchantNo:  "10001",
		storeId : 9,
		isWechat : "Y"

      },
      timeout: 10000,
      success(res) {
		if(res.statusCode === 401) {
			uni.showToast({
			  icon: 'none',
			  title: `登录失效，请重新登录`
			})
			 return setTimeout(()=>{
				 uni.reLaunch({
				    url: '/pages/auth/index'
				  })
			 }, 500)
		}



		if(res.data.code === 200 || res.data.code === 0) {
			resolve(res.data.data || res.data.result)
		}else{
			if(res.data.code === 1001) {
				uni.showToast({
				  icon: 'none',
				  title: `登录失效，请重新登录`
				})
				 return setTimeout(()=>{
					 uni.reLaunch({
					    url: '/pages/auth/index'
					  })
				 }, 500)
			}
			uni.showToast({
			  icon: 'none',
			  title: res.data.message|| "服务器出错，请稍等再试"
			})
			reject(res.data)
		}
      },
      fail(error) {
        uni.showToast({
          icon: 'none',
          title: `网络错误`
        })
        reject(error)
      },
      complete() {
        uni.hideLoading()
      }
    })
  })
}


Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

// const generateToken = () => {
//   return new Promise((resolve) => {
//     request(`/community/mini/auth/token`, "post", {}).then(res => {
//       resolve(res)
//     })
//   })

// }

// // 上传文件到 ali-oss
// const uploadFile = (filePath, res) => {
//   // 获取时间戳
//   const timestamp = Date.parse(new Date())
//   // 生成随机字符串
//   const randomStr = Math.random().toString(36).substr(2)

//   let fileType = filePath.split(".").pop();
//   let filename = res.data.bucket + '/' + +timestamp + randomStr + "." + fileType;
//   const region = res.data.region
//   const date = new Date();
//   date.setHours(date.getHours() + 1);
//   const policyText = {
//     expiration: date.toISOString(), // 设置policy过期时间。
//     conditions: [
//       ["content-length-range", 0, 1024 * 1024 * 1024],
//     ],
//   };
//   const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
//   const signature = getSignature(policy, res.data.token.AccessKeySecret); //获取签名
//   return new Promise((resolve, reject) => {
//     const formData = {
//       OSSAccessKeyId: res.data.token.AccessKeyId,
//       signature,
//       policy: policy,
//       'x-oss-security-token': res.data.token.SecurityToken,
//       key: filename,
//       success_action_status: 200
//     }
//     uni.uploadFile({
//       url: `https://${res.data.bucket}.${region}`,
//       filePath: filePath, //要上传文件资源的路径
//       name: 'file', //必须填file
//       formData: formData,
//       success: function (res1) {
//         if (res1.statusCode != 200) {
//           reject(new Error('上传错误:' + JSON.stringify(res1)))
//         } else {
//           resolve(`https://${res.data.bucket}.${region}` + '/' + filename + '?x-oss-process=style/y50')
//         }

//       },
//       fail: function (err) {
//         err.wxaddinfo = region;
//         reject(err);
//       },
//     })
//   })

// }


// const uploadFileToLocal = (filepath) =>{
//   return new Promise((resolve , reject) =>{
//     uni.uploadFile({
//       url: `${API_BASE_URL}/shop/h5/user/upload`,
//       header:{
//         'x-token': uni.getStorageSync('user-token'),
//       },
//       filePath: filepath, //要上传文件资源的路径
//       name: 'file', //必须填file
//       success: function (res) {
//         const response = JSON.parse(res.data)
//         if(response.code === 0){
//           resolve(response.data)
//         }else{
//           reject(response.msg)
//         }
//       },
//       fail: function (err) {
//         reject(err);
//       },
//     })
//   })
// }

const throttle = (fn, interval = 500) => {
  var last;
  return function () {
    var args = arguments;
    var now = +new Date();
    if (!last || now - last > interval) {
      last = now;
      fn.apply(this, args);
    }
  }
}



export {
  request,
  API_BASE_URL,
  throttle,
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + 2);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}


function getSignature(canonicalString, accessKeySecret) {
  // return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
